﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// RoleManager 的摘要描述
/// </summary>
public class RoleManager
{
	public RoleManager()
	{
		//
		// TODO: 在此加入建構函式的程式碼
		//
	}

    // org auth
    public List<string> GetCompForUser()
    {
        var db = new DB();
        var result = db.ExecuteListScalar<string>(string.Format("SELECT DISTINCT o.CompID FROM BranchData o WHERE BranchID IN ({0})",
                                                MyObj.JoinFormat(",", "'{0}'", RoleManager.Current.GetBranchForUser())));

        return result;
    }

    public List<string> GetBranchForUser()
    {
        var db = new DB();
        var result = db.ExecuteListScalar<string>(string.Format("SELECT DISTINCT o.BranchID FROM OrgData o WHERE OrgID IN ({0})",
                                                MyObj.JoinFormat(",", "'{0}'", RoleManager.Current.GetOrgForUser())));

        return result;
    }

    public List<int> GetOrgForUser()
    {
        var db = new DB();
        var result = db.ExecuteListScalar<int>(string.Format("SELECT o.OrgID FROM RoleOrgMap o WHERE RoleID IN ({0})",
                                                MyObj.JoinFormat(",", "'{0}'", RoleManager.Current.GetRolesForUser())));

        return result;
    }

    public List<int> GetOrgForCurrentComp()
    {
        var db = new DB();
        var result = db.ExecuteListScalar<int>(string.Format(@"SELECT o.OrgID FROM OrgData o
                                                INNER JOIN BranchData b ON o.BranchID = b.BranchID
                                                WHERE o.OrgID IN ({0}) AND b.CompID = @CompID ",
                                                MyObj.JoinFormat(",", "'{0}'", RoleManager.Current.GetOrgForUser())
                                                ), new DBParameter("CompID", OrgManager.Current.CurrentComp));

        return result;
    }

    // func auth
    public List<int> GetFuncsForUser()
    {
        var db = new DB();
        var result = db.ExecuteListScalar<int>(string.Format("SELECT DISTINCT rf.FuncID FROM RoleFuncMap rf WHERE RoleID IN ({0})",
                                                MyObj.JoinFormat(",", "'{0}'", RoleManager.Current.GetRolesForUser())));

        return result;
    } 

    // user roles list
    public string[] GetRolesForUser()
    {
        return (new MyRoleProvider()).GetRolesForUser(EmpManager.Current.UserName);
    }

    //

    public static RoleManager Current
    {
        get
        {
            if (HttpContext.Current.Items["RoleManager"] == null)
            {
                HttpContext.Current.Items["RoleManager"] = new RoleManager();
            }

            return HttpContext.Current.Items["RoleManager"] as RoleManager;
        }
    }
}